package com.thinkfit.jy.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.common.lib.bean.ApplicationBean;
import com.common.lib.constant.EventBusEvent;
import com.thinkfit.jy.R;
import com.thinkfit.jy.adapter.RunningApkAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.annotations.NonNull;

/**
 * 返回按钮（用于在第三方应用中返回本应用）
 */
public class ApkListViewUtils implements View.OnClickListener {
    private static ApkListViewUtils apkListViewUtils;
    WindowManager windowManager;
    WindowManager.LayoutParams layoutParams;
    Context mContext;
    boolean isFist = true;

    View inflate;
    ImageView ivHome,ivSet;
    RecyclerView rvApp;
    ArrayList<ApplicationBean> appList = new ArrayList<>();
    LinearLayout llApk;
    ArrayList<View> ivs = new ArrayList<>();
    ArrayList<String> images = new ArrayList<>();
    float posX,posY,curPosX,curPosY,width,x;
    RunningApkAdapter runningApkAdapter;

    private static int OPEN_APP_NUM = 1;//开启应用数
    public static ApkListViewUtils getInstance(){
        if(apkListViewUtils == null){
            apkListViewUtils = new ApkListViewUtils();
        }
        return apkListViewUtils;
    }


    public void initView(Context context){
        mContext = context;
        if(windowManager == null){
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        if(inflate == null){
            inflate = LayoutInflater.from(context).inflate(R.layout.item_apk_list, null);
            ivHome = inflate.findViewById(R.id.iv_home);
            ivSet = inflate.findViewById(R.id.iv_set);
            llApk = inflate.findViewById(R.id.ll_apk);
            rvApp = inflate.findViewById(R.id.rv_apk);
            width = inflate.getWidth();

            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext,4);
            rvApp.setLayoutManager(gridLayoutManager);
            runningApkAdapter = new RunningApkAdapter(mContext);
            runningApkAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    ApplicationBean applicationBean = (ApplicationBean) adapter.getData().get(position);
//                    applicationBean.setForeground(true);
                    RunningAppUtils.getInstance().init(mContext);
//                    adapter.notifyItemChanged(position);
                    if(applicationBean.getOpenStatus() == 1){
                        PackageManager packageManager = mContext.getPackageManager();
                        Intent intent = packageManager.getLaunchIntentForPackage(applicationBean.getAppid());
                        if (intent != null) {
                            mContext.startActivity(intent);
                        }
                        applicationBean.setOpenStatus(1);
//                        SystemUtils.setTopApp(mContext,applicationBean.getAppid());
                    }else {
                        RunningAppUtils.getInstance().init(mContext);
                        ArrayList<ApplicationBean> currentRunningApp = RunningAppUtils.getInstance().getCurrentRunningApp();
                        boolean isOpen = RunningAppUtils.getInstance().isOpen(applicationBean.getAppid());
                        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   isOpen : "+isOpen);

                        if(!isOpen){//是否已经打开
                            if(currentRunningApp.size() >= OPEN_APP_NUM){
                                DialogCloseApkViewUtils.getInstance().initView(mContext,applicationBean.getAppid());
                            }else {
                                PackageManager packageManager = mContext.getPackageManager();
                                Intent intent = packageManager.getLaunchIntentForPackage(applicationBean.getAppid());
                                if (intent != null) {
                                    mContext.startActivity(intent);
                                }
                                ((ApplicationBean) adapter.getData().get(position)).setOpenStatus(1);
                            }
                        }else {
                            PackageManager packageManager = mContext.getPackageManager();
                            Intent intent = packageManager.getLaunchIntentForPackage(applicationBean.getAppid());
                            if (intent != null) {
                                mContext.startActivity(intent);
                            }
                            ((ApplicationBean) adapter.getData().get(position)).setOpenStatus(1);
                        }
                    }
                    for (int i=0;i<adapter.getData().size();i++){
                        if(i == position){
                            ((ApplicationBean) adapter.getData().get(i)).setForeground(true);
                        }else {
                            ((ApplicationBean) adapter.getData().get(i)).setForeground(false);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    goneButton();
                }
            });
            runningApkAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    ApplicationBean applicationBean = (ApplicationBean) adapter.getData().get(position);
                    DialogViewUtils.getInstance().setClosePackageName(applicationBean.getAppid());
                    DialogViewUtils.getInstance().initView(mContext,false,DialogViewUtils.EXIT_APP);
                    ((ApplicationBean) adapter.getData().get(position)).setOpenStatus(0);
                    adapter.notifyItemChanged(position);
                    goneButton();
                    return false;
                }
            });
            rvApp.setAdapter(runningApkAdapter);
            ivHome.setOnClickListener(this);
            ivSet.setOnClickListener(this);
        }
//        llApk.removeAllViews();
//
//        ArrayList<View> imageViews = initApkList();
//
//        for (View iv : imageViews){
//            llApk.addView(iv);
//        }
        getAppList(mContext);
        if(appList != null && appList.size() >0){
            runningApkAdapter.setNewInstance(appList);
        }


        if(layoutParams == null){
            layoutParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT
            );

            layoutParams.gravity = Gravity.CENTER| Gravity. BOTTOM;
            layoutParams.y = dp2px(85);
        }

        if(isFist){
            isFist = false;
            windowManager.addView(inflate,layoutParams);
        }else {
            inflate.setVisibility(View.VISIBLE);
        }

    }

    public void setOpenStatus(String appid,boolean isOpen){
        if(inflate != null){
            if(runningApkAdapter != null && runningApkAdapter.getData().size()>0){
                for (int i=0;i<runningApkAdapter.getData().size();i++){
                    if(appid.equals(runningApkAdapter.getData().get(i).getAppid())){
                        if(isOpen){
                            runningApkAdapter.getData().get(i).setOpenStatus(1);
                        }else {
                            runningApkAdapter.getData().get(i).setOpenStatus(0);
                        }

                    }
                }

            }
            runningApkAdapter.notifyDataSetChanged();
        }
    }

    public void backHome(){
        if(inflate != null){
            if(runningApkAdapter != null && runningApkAdapter.getData().size()>0){
                for (int i=0;i<runningApkAdapter.getData().size();i++){
                    runningApkAdapter.getData().get(i).setOpenStatus(0);
                }
            }
            runningApkAdapter.notifyDataSetChanged();
        }
    }

    public ArrayList<View> initApkList(){
        ivs.clear();
        images.clear();
        RunningAppUtils.getInstance().init(mContext);
        ArrayList<ApplicationBean> currentRunningApp = RunningAppUtils.getInstance().getCurrentRunningApp();
        for (int i = 0;i< currentRunningApp.size();i++){
            System.out.println("ddddddddddddddddddddddd  applicationBean "+currentRunningApp.get(i).getAppid());
            images.add(currentRunningApp.get(i).getIcon());
            View itemApk = LayoutInflater.from(mContext).inflate(R.layout.item_apk, null);
            ImageView iv_apk_icon = itemApk.findViewById(R.id.iv_apk_icon);
            ImageView iv_apk_un = itemApk.findViewById(R.id.iv_apk_un);
            iv_apk_un.setVisibility(View.GONE);
            if(SystemUtils.isForeground(mContext,currentRunningApp.get(i).getAppid())){
                System.out.println("ddddddddddddddddddddddd  当前置顶是  :   "+currentRunningApp.get(i).getAppid());
                iv_apk_un.setVisibility(View.VISIBLE);
            }

            ImageLoadUtils.getInstance(mContext).setImageUtlRadius(iv_apk_icon,images.get(i),0,11);
            int finalI = i;
            iv_apk_icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(SystemUtils.isAppRunning(mContext,currentRunningApp.get(finalI).getAppid())){
                        SystemUtils.setTopApp(mContext,currentRunningApp.get(finalI).getAppid());
                    }else {
//                        RunningAppUtils.getInstance().init(mContext);
//                        ArrayList<ApplicationBean> currentRunningApp = RunningAppUtils.getInstance().getCurrentRunningApp();
//                        boolean isOpen = RunningAppUtils.getInstance().isOpen(currentRunningApp.get(finalI).getAppid());
//                        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   isOpen : "+isOpen);
//                        if(!isOpen){//是否已经打开
//                            if(currentRunningApp.size()>=3){
//                                DialogCloseApkViewUtils.getInstance().initView(mContext,currentRunningApp.get(finalI).getAppid());
//                            }else {
//                                PackageManager packageManager = mContext.getPackageManager();
//                                Intent intent = packageManager.getLaunchIntentForPackage(currentRunningApp.get(finalI).getAppid());
//                                if (intent != null) {
//                                    mContext.startActivity(intent);
//                                }
//                            }
//                        }else {
//                            Intent intent2 = new Intent(Intent.ACTION_DELETE);
//                            intent2.setData(Uri.parse("package:" + currentRunningApp.get(finalI).getAppid()));
//                            intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            mContext.startActivity(intent2);
//                        }
                        Intent intent2 = new Intent(Intent.ACTION_DELETE);
                        intent2.setData(Uri.parse("package:" + currentRunningApp.get(finalI).getAppid()));
                        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(intent2);

                    }

                    goneButton();

                }
            });
            iv_apk_icon.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    DialogViewUtils.getInstance().setClosePackageName(currentRunningApp.get(finalI).getAppid());
                    DialogViewUtils.getInstance().initView(mContext,false,DialogViewUtils.EXIT_APP);
                    return false;
                }
            });
            ivs.add(itemApk);
        }
        return ivs;
    }


    public void initAppList(Context context,ArrayList<ApplicationBean> list){
        appList.clear();
        PackageManager packageManager = context.getPackageManager();
        // 获取已安装的app信息
        List<PackageInfo> pkgInfos = packageManager.getInstalledPackages(0);
        if (pkgInfos != null) {
            for (ApplicationBean bean : list) {
                for (PackageInfo info : pkgInfos) {
                    //  Log.e("aaaaaaaaaa", info.packageName+", "+info.applicationInfo.loadLabel(packageManager).toString());
                    if (bean.getAppid().equals(info.packageName)) {
//                        bean.setInstallStatus(2);
                        appList.add(bean);
                        break;
                    }
                }
            }
        }
//        appHomeAdapter.setNewInstance(appList);
        getAppList(context);
    }

    public void getAppList(Context context){
        RunningAppUtils.getInstance().init(context);
        ArrayList<ApplicationBean> currentRunningApp = RunningAppUtils.getInstance().getCurrentRunningApp();
        for (int i=0;i<appList.size();i++){
            for (int y=0;y<currentRunningApp.size();y++){
                if(appList.get(i).getAppid().equals(currentRunningApp.get(y).getAppid())){
                    appList.get(i).setOpenStatus(1);
                }
            }
        }

//        runningApkAdapter.setNewInstance(appList);
//        return appList;
    }

    public void goneButton(){
        if(windowManager != null){
            if(inflate != null){
                inflate.setVisibility(View.GONE);
                HashMap<String, Object> map = new HashMap<>();
                map.put(EventBusEvent.IS_SHOW_APP,false);
                EventBus.getDefault().post(map);
            }
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_home:
//                if(!SystemUtils.isForeground(mContext,mContext.getPackageName())){
////                    Intent intent = new Intent();
////                    ComponentName componentName = new
////                            ComponentName(mContext.getPackageName(), MainActivity.class.getName());
//////                        ComponentName("com.thinkfit.ride",activityName);
////                    intent.setComponent(componentName);
////                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
////                    startActivity(intent);
//                    SystemUtils.setTopApp(mContext,mContext.getPackageName());
//                    System.out.println("ddddddddddddddddddddddd  inflate GONE");
////                    inflate.setVisibility(View.GONE);
//                    ShowSpeedViewUtils.getInstance().goneLayout();
////                    BackButtonViewUtils.getInstance().goneButton();
//                    goneButton();
//                }
                SystemUtils.setTopApp(mContext,mContext.getPackageName());
                System.out.println("ddddddddddddddddddddddd  inflate GONE");
                boolean isRun = MotionDataUtils.getInstance().isRun();
                if(!isRun){
                    ShowSpeedViewUtils.getInstance().goneLayout();
                }
                for (int i=0;i<runningApkAdapter.getData().size();i++){
                    runningApkAdapter.getData().get(i).setForeground(false);
                }
                runningApkAdapter.notifyDataSetChanged();
                goneButton();
                break;
            case R.id.iv_set:
                VolumeAndBrightnessViewUtils.getInstance().initView(mContext);
                goneButton();
                break;
        }
    }

    /**
     * dp2px
     */
    protected int dp2px(float dpValue) {
        float density = mContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5f);
    }
}
